//
//  RootViewController.m
//  SelectionForYou
//
//  Created by qianfeng on 15-6-8.
//  Copyright (c) 2015年 朱共营. All rights reserved.
//

#import "RootViewController.h"
#import "AFNetworking.h"
#import "MyCell.h"
#import "MyModel.h"
#import "SecenddViewController.h"
#import "SearchViewController.h"
#import "SettingViewController.h"
#import "JHRefresh.h"
#import "MMProgressHUD.h"
#import "MyControl.h"
#define kUrl @"http://apis.guokr.com/handpick/article.json?retrieve_type=by_since&since=%ld&orientation=before&category=all&ad=1"
#define kUrlDownlod @"http://apis.guokr.com/handpick/article.json?retrieve_type=by_since&since=%ld&orientation=before"
#define kScreenSize [UIScreen mainScreen].bounds.size

@interface RootViewController ()<UISearchBarDelegate>
{
    NSString *_lastDate;
}
@property(nonatomic,copy) NSString *lastDate;
@end

@implementation RootViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self addItemWithTitle:@"设置" target:self action:@selector(btnClick:) isLeft:YES];
    [self addItemWithTitle:@"刷新" target:self action:@selector(btnRefrash:) isLeft:NO];
    [self creatLaunchImageAnimation];
    self.title=@"猪哥推荐";
   
    //self.automaticallyAdjustsScrollViewInsets=NO;
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed: @"navigationbar"] forBarMetrics:UIBarMetricsDefault];
    _manager=[AFHTTPRequestOperationManager manager];
   _manager.responseSerializer=[AFHTTPResponseSerializer serializer];
   _dataArr=[[NSMutableArray alloc] init];
   
   
    
    
    [self creatTableView];
    //  [self downloadDataWithUrl:kUrl];
    [self firstDownload];
    [self creatRefreshView];
}

- (void)creatTableView{
    
    self.tabBarController.hidesBottomBarWhenPushed=NO;
    self.automaticallyAdjustsScrollViewInsets=NO;
    self.tableView=[[UITableView alloc] initWithFrame:CGRectMake(0, 0, kScreenSize.width, kScreenSize.height-64) style:UITableViewStylePlain];
    
    [self.tableView registerNib:[UINib nibWithNibName:@"MyCell" bundle:nil] forCellReuseIdentifier:@"MyCell"];
    self.tableView.delegate=self;
    self.tableView.dataSource=self;
 //
    [self.view addSubview:self.tableView];
    UISearchBar *searchBar=[[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, self.tableView.bounds.size.width, 44)];
    searchBar.delegate=self;
    searchBar.placeholder=@"等你来插";
    self.tableView.tableHeaderView=searchBar;
    
    
}
- (void)creatLaunchImageAnimation{
    UIImageView *starView=[MyControl creatImageViewWithFrame:self.view.bounds imageName:[NSString stringWithFormat:@"Defaultretein%u",arc4random()%7+1]];
    [self.view addSubview:starView];
    [UIView animateWithDuration:10 animations:^{
        starView.alpha=0;
    }completion:^(BOOL finished) {
        [starView removeFromSuperview];
    }];

    NSLog(@"122");
}
//导航左右按钮
- (void)addItemWithTitle:(NSString *)title target:(id)target action:(SEL)action isLeft:(BOOL)isLeft{
    UIButton *button=[MyControl creatButtonWithFrame:CGRectMake(0, 0, 50, 30) target:target sel:action tag:100 image:@"buttonbar_action" title:title];
    [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    
    UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithCustomView:button];
    if (isLeft) {
        self.navigationItem.leftBarButtonItem = item;
    }else{
        self.navigationItem.rightBarButtonItem = item;
    }



}
- (void)btnRefrash:(UIButton *)btn{
    NSLog(@"zaishuxin");
    [self.tableView scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:YES];
   //
    [self downloadDataWithUrl:kUrl];
    
    
}

- (void)btnClick:(UIButton *)ntb{
    SettingViewController *set=[[SettingViewController alloc] init] ;
    [self.navigationController pushViewController:set animated:YES];

}
- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar{
    [searchBar setShowsCancelButton:YES animated:YES];
    return YES;

}
- (BOOL)searchBarShouldEndEditing:(UISearchBar *)searchBar{
    [searchBar setShowsCancelButton:NO animated:YES];
    return YES;

}
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar{
    [searchBar resignFirstResponder];
    searchBar.text=@"";

}
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{

    [searchBar resignFirstResponder];
    
    
    
    
    SearchViewController *searchView=[[SearchViewController alloc] init];
    searchView.source_name=searchBar.text;
    [self.navigationController pushViewController:searchView animated:YES];

}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
    
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
 //   NSLog(@"%ld",self.dataArr.count);
    
        return self.dataArr.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
   
        MyModel *model=_dataArr[indexPath.row];
    
        MyCell *cell=[tableView dequeueReusableCellWithIdentifier:@"MyCell" forIndexPath:indexPath];
        [cell showDataWithModel:model];
    
        
        return cell;
    
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    MyModel *model=_dataArr[indexPath.row];
  
    
   SecenddViewController *secend=[[SecenddViewController alloc] init];
    secend.idd=model.id;
    secend.headline_img_tb=model.headline_img_tb;
    secend.link_v2=model.link_v2;
    secend.titleHose=model.title;
    [self.navigationController pushViewController:secend animated:YES];
  
   // NSLog(@"%@",model1.id);
    

}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{

    return 97;
}
- (void)downloadDataWithUrl:(NSString *)url{
   
         NSString *url1=[NSString stringWithFormat:kUrl];
   
    
   
    __weak typeof(self)weakMyself=self;
   [_manager GET:url1 parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSLog(@"下载成功");
       [weakMyself.dataArr removeAllObjects];
       NSDictionary *dict=[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
       NSArray *arr=dict[@"result"];
       int i=0;
       for (NSDictionary *appDict in arr) {
           
           MyModel *model=[[MyModel alloc] init];
           [model setValuesForKeysWithDictionary:appDict];
         //  NSLog(@"%d",model.id.intValue);
          i++;
               [weakMyself.dataArr addObject:model];
             //  NSLog(@"model:%@",model.title);
           
              //  NSLog(@"_dataArr:%@",model.source_name);
           if (i==arr.count) {
//NSLog(@"%d",i);
              
               self.lastDate=model.date_picked;
               // NSLog(@"%d",self.lastDate.intValue);
           }
          
           NSLog(@"%@", model.page_source);
      //
          NSLog(@"%ld",(long)_lastDate);
          
           
       }
       [weakMyself.tableView reloadData];
       
       [weakMyself endRefreshing];
    
       
       
   } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
       NSLog(@"下载失败");
   }];

}

- (void)firstDownload{
  //  self.isRefreshing=NO;
    self.isLoadMoring=NO;
   
    [self downloadDataWithUrl:kUrl];
    //[self creatRefreshView];

}
- (void)addTaskUrl:(NSString *)url isRefresh:(BOOL)isRefresh{
    //url=[NSString stringWithFormat:url];
    __weak typeof (self) weakSelf = self;
    
    if (_isRefreshing) {
        return;
    }
    _isLoadMoring=YES;
    
    [_manager GET:url parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSLog(@"刷新成功");
       
        if (responseObject) {
            NSDictionary *dict=[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
            NSArray *arr=dict[@"result"];
             int i=0;
            for (NSDictionary *appDict in arr) {
                i++;
                MyModel *model=[[MyModel alloc] init];
                [model setValuesForKeysWithDictionary:appDict];
                [weakSelf.dataArr addObject:model];
                NSLog(@"%d",i);
                if (i==arr.count) {
                    NSLog(@"%@",weakSelf.lastDate);
                    weakSelf.lastDate=model.date_picked;
                  //./  NSLog(@"%@");
                }
                
            }
            [weakSelf.tableView reloadData];
            [weakSelf endRefreshing];
            NSLog(@"%d",_isLoadMoring);
        }
        
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"刷新下载失败");
        [weakSelf endRefreshing];
    }];

}
- (void)creatRefreshView{
    __weak typeof(self)weakSelf=self;
    NSLog(@"1");
    [self.tableView addRefreshFooterViewWithAniViewClass:[JHRefreshCommonAniView class] beginRefresh:^{
        //上啦加载更多
        if (weakSelf.isLoadMoring) {
             [weakSelf endRefreshing];
            return ;
            NSLog(@"1");
        }
         NSString *str=[NSString stringWithFormat:kUrlDownlod,weakSelf.lastDate.intValue];
        NSLog(@"%@",str);
       // NSLog(@"%d",self.lastDate.intValue);
        weakSelf.isLoadMoring=NO;
        
       
        [weakSelf addTaskUrl:str isRefresh:YES];
        weakSelf.lastDate=nil;
       
    }];

   
    
    
}
- (void)endRefreshing{
    if (self.isLoadMoring) {
        self.isLoadMoring=NO;
        [self.tableView footerEndRefreshing];
    }
    if (self.isRefreshing) {
        self.isRefreshing =NO;
        [self.tableView headerEndRefreshingWithResult:JHRefreshResultSuccess];
    }

}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
